<template>
	<view class="content">
		<view class="body">
			<view>
				<textarea class="result" v-model="returnResult"></textarea>
			</view>
			<textarea class="input" @input="inputEvent" />
			<button type="primary" @tap="sendData">发送(票据可使用)</button>

			<view style='margin-top:4%;display: flex;flex-direction: row;'>
				<button type='primary' @tap='receiptTest' :loading='isReceiptSend' :disabled='isReceiptSend'>票据测试</button>
				<button type='primary' @tap='labelTest' :loading='isLabelSend' :disabled='isLabelSend'>标签测试</button>
			</view>

			<view style='margin-top:4%;display: flex;flex-direction: row;'>
				<!-- hidden='true' -->
				<canvas canvas-id='edit_area_canvas' :style="{width:canvasWidth+'px',height:canvasHeight+'px'}"></canvas>
			</view>

			<picker style='margin:20px' mode='selector' :range='buffSize' :value='buffIndex' @change='buffBindChange'>
				当前每次发送字节数为(点击可更换)：{{buffSize[buffIndex]}}
			</picker>

			<picker style='margin:20px' mode='selector' :range='printNum' :value='printNumIndex' @change='printNumBindChange'>
				当前打印份数(点击可更换)：{{printNum[printNumIndex]}}
			</picker>

		</view>
	</view>
</template>

<script>
	var tsc = require("@/util/ble/tsc.js");
	var esc = require("@/util/ble/esc.js");
	var encode = require("@/util/ble/encoding.js");
	import {
		mapState
	} from 'vuex';
	import {
		momenyFormat
	} from '@/util/util.js'
	export default {
		props: {
			printData: {
				require: true,
				type: Object,
				default: {}
			},
			data: {
				require: true,
				type: Array,
				default: []
			},
			Sign: {
				require: false,
				type: String,
				default: ''
			}
		},
		data() {
			return {
				sendContent: "",
				looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				returnResult: "",
				canvasWidth: 180,
				canvasHeight: 180,
				imageSrc: '',
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isReceiptSend: false,
				isLabelSend: false,
				dealy: 5
			};
		},
		computed: mapState(['sysinfo', 'Bluetooth']),
		onLoad() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
		},
		mounted() {
			console.log('激活了');
			this.init()
		},
		onUnload() {
			let that = this;
			let {
				BLEInformation
			} = that.Bluetooth;
			// uni.closeBLEConnection({
			//      deviceId: BLEInformation.deviceId,
			//      success: function(res) {
			//        console.log("关闭蓝牙成功")
			//      },
			//    })	
		},
		methods: {
			init() {
				let list = []
				let numList = []
				let j = 0
				for (let i = 20; i < 200; i += 20) {
					list[j] = i;
					j++
				}
				for (let i = 1; i < 10; i++) {
					numList[i - 1] = i
				}
				this.buffSize = list;
				this.oneTimeData = list[0];
				this.printNum = numList;
				this.printerNum = numList[0];
				if (uni.getSystemInfoSync().platform == 'ios') this.dealy = 0
				else this.dealy = 5
			},
			//获取输入内容
			inputEvent(e) {
				this.sendContent = e.detail.value;
			},
			//输入框点击发送
			sendData() {
				let data = this.sendContent + "\n"
				this.looptime = 0;
				var content = new encode.TextEncoder(
					'gb18030', {
						NONSTANDARD_allowLegacyEncoding: true
					}).encode(data);

				this.prepareSend(content);
			},
			//标签测试
			labelCode() {
				uni.showLoading({
					mask: true,
					title: '打印中...'
				})
				let that = this;
				let command = tsc.jpPrinter.createNew()
				// code 18
				command.setSize(90, 50)
				command.setGap(0)
				command.setCls()
				//二维码
				command.setText(250, 15, "TSS24.BF2", 1, 1, '赊货签')
				command.setQR(185, 70, "L", 15, "A", this.printData.code)
				command.setText(170, 300, "TSS24.BF2", 1, 1, '扫一扫二维码定位商家')
				command.setPagePrint()
				that.isLabelSend = true;
				that.prepareSend(command.getData())
			},

			//标签测试
			labelTest() {
				uni.showLoading({
					mask: true,
					title: '打印中...'
				})
				let that = this;
				let canvasWidth = that.canvasWidth
				let canvasHeight = that.canvasHeight
				let command = tsc.jpPrinter.createNew()
				//      (基础高度+二维码)  列表高度
				// let height = 100 + ((this.data.length + 1) * 7.5)
				let height = 100
				if (this.data.length < 30) {
					height += ((this.data.length + 1) * 8.5)
				} else if (this.data.length >= 30 && this.data.length < 80) {
					height += ((this.data.length + 1) * 9)
				} else {
					height += ((this.data.length + 1) * 15)
				}
				// code 18
				console.log(height);
				command.setSize(90, height)
				command.setGap(0)
				command.setCls()
				command.setText(0, 1, "TSS24.BF2", 1, 1, this.printData.CompanyName)

				// 编号前面的s或b
				let orderName = ""
				if (this.printData.OrderType == 1) {
					orderName = "B"
				} else {
					orderName = "S"
				}
				//单号
				let orderId = orderName + this.printData.Id
				let newOrderId = orderId.replace(/\s/g, '').replace(/(.{4})/g, "$1 ")
				command.setText(0, 30, "TSS24.BF2", 1, 1, "单号：" + (newOrderId))
				//日期
				let time = this.printData.CreateTime ? this.printData.CreateTime.substring(0, 19) : ''
				command.setText(0, 60, "TSS24.BF2", 1, 1, "时间：" + time)

				// 账期
				let Period = ""
				// // 客户名称的打印上下边距
				let bottomCusName = 0
				// 客户地址的打印上下边距
				let bottomcCusAddress = 0
				// 客户电话的打印上下边距
				let bottomcCusPhone = 0
				if (this.printData.OrderType == 1) {
					Period = this.printData.Period + ' 天 '
					command.setText(0, 90, "TSS24.BF2", 1, 1, "账期：" + Period)
					bottomCusName = 120
					bottomcCusAddress = 150
					bottomcCusPhone = 180

				} else {
					bottomCusName = 90
					bottomcCusAddress = 120
					bottomcCusPhone = 150
				}

				//客户
				let customer = this.printData.cCusName || '散客'
				command.setText(0, bottomCusName, "TSS24.BF2", 1, 1, "客户：" + customer)
				//客户地址
				let cusAddress = this.printData.cCusAddress || ''
				command.setText(0, bottomcCusAddress, "TSS24.BF2", 1, 1, "客户地址：" + cusAddress)
				//客户电话
				let cusPhone = this.printData.cCusPhone || ''
				command.setText(0, bottomcCusPhone, "TSS24.BF2", 1, 1, "客户电话：" + cusPhone)


				//列表 固定到此位置 高度为 23mm 290 是整个表单区域的上下边距
				command.setText(0, 290, "TSS24.BF2", 1, 1, "")
				command.setText(40, 290, "TSS24.BF2", 1, 1, "编码/品名")
				command.setText(230, 290, "TSS24.BF2", 1, 1, "数量")
				// command.setText(290, 260, "TSS24.BF2", 1, 1, "单位")
				command.setText(320, 290, "TSS24.BF2", 1, 1, "单价")
				command.setText(450, 290, "TSS24.BF2", 1, 1, "金额")
				let length = this.data.length + 1
				this.data.forEach((item, index) => {
					console.log(item);
					let space = (index + 1) * 70
					let InventName = item.InventName ? item.InventName.substring(0, 7) : '' // 品名
					let Quantity = item.Quantity || 0 // 数量
					command.setText(0, 290 + space - 30, "TSS24.BF2", 1, 1, (index + 1) + '.')
					command.setText(40, 290 + space - 30, "TSS24.BF2", 1, 1, InventName)
					command.setText(230, 290 + space - 30, "TSS24.BF2", 1, 1, Quantity)
					// command.setText(290, 260 + space - 30, "TSS24.BF2", 1, 1, GroupName)
					command.setText(320, 290 + space - 30, "TSS24.BF2", 1, 1, momenyFormat(item.Price))
					command.setText(450, 290 + space - 30, "TSS24.BF2", 1, 1, momenyFormat(item.Money))
					let cInvCode = item.cInvCode ? item.cInvCode.substring(0, 16) : '' // 编码
					let GroupName = item.GroupName || '' // 单位
					let cInvStd = item.cInvStd || '' // 规格
					command.setText(40, 290 + space, "TSS24.BF2", 1, 1, cInvCode)
					command.setText(230, 290 + space, "TSS24.BF2", 1, 1, GroupName)
					if (item.cInvStd) {
						command.setText(320, 290 + space, "TSS24.BF2", 1, 1, "规格:" + cInvStd)
					}
					console.log('11111');
				})
				//列表高度+原本高度+合计高度
				let newY = 280 + (length * 70)
				//合计
				command.setText(30, newY, "TSS24.BF2", 1, 1, '总数: ' + this.printData.TotalQuantity)
				command.setText(170, newY, "TSS24.BF2", 1, 1, "合计：" + momenyFormat(this.printData.TotalSum))
				// 实收
				let payType = ''
				// 赊货
				if (this.printData.Type == 1) {
					command.setText(380, newY, "TSS24.BF2", 1, 1, '赊货: ' + momenyFormat(this.printData.PendingSum))
				} else {
					payType = this.printData.PaymentType
					command.setText(380, newY, "TSS24.BF2", 1, 1, payType + "：" + momenyFormat(this.printData.ReceiveSum))
				}

				//小票短语
				let str = uni.getStorageSync('ReceiptPhrase')
				command.setText(0, newY + 70, "TSS24.BF2", 1, 1, str)
				//二维码
				command.setQR(230, newY + 110, "L", 5, "A", 'https://hzq.yoojet.com/#/App/Receipt?Id=' + this.printData.Id)
				// command.setText(15, newY + 260, "TSS24.BF2", 1, 1, '扫码查看')
				command.setText(250, newY + 260, "TSS24.BF2", 1, 1, '电子小票')
				// 个人二维码及收款二维码
				let userInfo = uni.getStorageSync('userInfo')
				// 暂时不要删除  后续需要打开
				// if (userInfo.WeChatUser) {
				// 	command.setQR(200, newY + 110, "L", 5, "A", userInfo.WeChatUser)
				// 	command.setText(220, newY + 260, "TSS24.BF2", 1, 1, '加我微信')
				// }
				// if (userInfo.WeChatPay) {
				// 	command.setQR(400, newY + 110, "L", 5, "A", userInfo.WeChatPay)
				// 	command.setText(420, newY + 260, "TSS24.BF2", 1, 1, '微信支付')
				// }
				// 地址
				let address = this.printData.Address || ''
				command.setText(0, newY + 340, "TSS24.BF2", 1, 1, '地址：' + address)
				command.setText(170, newY + 400, "TSS24.BF2", 1, 1, '赊货签提供技术支持')
				command.setPagePrint()
				that.isLabelSend = true;
				that.prepareSend(command.getData())
			},

			//票据测试
			receiptTest() {
				uni.showLoading({
					mask: true,
					title: '打印中...'
				})
				var that = this;
				var canvasWidth = that.canvasWidth
				var canvasHeight = that.canvasHeight
				var command = esc.jpPrinter.createNew()
				command.init()
				// 标题
				command.bold(1); //加粗
				command.setFontSize(16); //字体大小
				command.setSelectJustification(1) //居中
				command.rowSpace(100);
				command.setText(this.printData.CompanyName);
				command.setPrint();
				command.rowSpace(60);

				command.bold(0); //取消加粗
				command.setFontSize(0); //正常字体
				//单号
				command.setSelectJustification(0); //居左
				//单号
				let orderId = orderName + this.printData.Id
				let newOrderId = orderId.replace(/\s/g, '').replace(/(.{4})/g, "$1 ")
				command.setText("单号：" + newOrderId);
				command.setPrint();
				//日期
				let time = this.printData.CreateTime ? this.printData.CreateTime.substring(0, 19) : ''
				command.setSelectJustification(0); //居左
				command.setText("日期：" + time);
				command.setPrint();
				// 账期
				let Period = ""
				if (this.printData.OrderType == 1) {
					Period = this.printData.Period + ' 天 '
					command.setSelectJustification(0); //居左
					command.setText("账期：" + Period);
					command.setPrint();
				}

				//客户
				let customer = this.printData.cCusName || '散客'
				command.setSelectJustification(0); //居左
				command.setText("客户：" + customer);
				command.setPrint(); //打印并走纸feed个单位
				//业务员
				let RealName = this.printData.RealName || ''
				command.setSelectJustification(0); //居左
				command.setText("业务员：" + RealName);
				command.setPrintAndFeed(80); //打印并走纸feed个单位
				//列表
				command.rowSpace(80); //间距
				command.bold(5); //加粗
				command.setText("");
				command.setAbsolutePrintPosition(25);
				command.setText("品名");
				command.setAbsolutePrintPosition(220);
				command.setText("数量");
				command.setAbsolutePrintPosition(350);
				command.setText("单价");
				command.setAbsolutePrintPosition(450);
				command.setText("金额");
				command.setPrint()
				command.bold(0); //加粗
				// 循环
				this.data.forEach((item, index) => {
					if (item.InventName.length <= 8) {
						command.setText(index + 1);
						command.setAbsolutePrintPosition(25);
						command.setText(item.InventName);
						command.setAbsolutePrintPosition(220);
						command.setText(item.Quantity || 0);
						command.setAbsolutePrintPosition(350);
						command.setText(momenyFormat(item.Price));
						command.setAbsolutePrintPosition(450);
						command.setText(momenyFormat(item.Money));
						command.setPrint()
					} else {
						for (var i = 0; i <= item.InventName.length; i += 7) {
							if (i == 0) {
								command.setText(index + 1);
								command.setAbsolutePrintPosition(25);
								command.setText(item.InventName.substring(i, i + 7));
								command.setAbsolutePrintPosition(220);
								command.setText(item.Quantity || 0);
								command.setAbsolutePrintPosition(350);
								command.setText(momenyFormat(item.Price));
								command.setAbsolutePrintPosition(450);
								command.setText(momenyFormat(item.Money));
								command.setPrint()
							} else {
								command.setText();
								command.setAbsolutePrintPosition(25);
								command.setText(item.InventName.substring(i, i + 7));
								command.setAbsolutePrintPosition(220);
								command.setText();
								command.setAbsolutePrintPosition(350);
								command.setText();
								command.setAbsolutePrintPosition(480);
								command.setText();
								command.setPrint()
							}
						}
					}
				})

				//合计
				command.bold(5); //加粗
				command.setAbsolutePrintPosition(120);
				command.setText("总数：" + this.printData.TotalQuantity);
				command.setAbsolutePrintPosition(320);
				command.setText("合计：" + momenyFormat(this.printData.TotalSum));
				command.setPrint();
				command.setAbsolutePrintPosition(120);
				command.setAbsolutePrintPosition(320);
				// 实收
				let payType = ''
				// 赊货
				if (this.printData.Type == 1) {
					command.setText("赊货：" + momenyFormat(this.printData.PendingSum));
				} else {
					payType = this.printData.PaymentType
					command.setText(payType + "：" + momenyFormat(this.printData.ReceiveSum));
				}
				command.setPrintAndFeedRow(2);
				//小票短语
				let str = uni.getStorageSync('ReceiptPhrase')
				command.rowSpace(80); //间距
				command.bold(2); //加粗
				command.setSelectJustification(1); //居中
				command.setText(str)
				command.setPrintAndFeedRow(2);
				//二维码
				command.setSelectJustification(1); //居中
				command.setStoreQRCodeData('https://hzq.yoojet.com/#/App/Receipt?Id=' + this.printData.Id)
				command.setSelectSizeOfModuleForQRCode(8)
				command.setPrintQRCode()
				command.setPrintAndFeed(30);
				//提示
				command.setText("扫码查看电子小票");
				command.setPrintAndFeedRow(2);
				// 个人二维码及收款二维码
				let userInfo = uni.getStorageSync('userInfo')
				console.log(userInfo);
				// if (userInfo.WeChatUser) {
				// 	command.setStoreQRCodeData(userInfo.WeChatUser)
				// 	command.setSelectSizeOfModuleForQRCode(8)
				// 	command.setPrintQRCode()
				// 	command.setPrintAndFeed(30);
				// 	command.setText('加我微信')
				// 	command.setPrintAndFeedRow(2);
				// }
				// if (userInfo.WeChatPay) {
				// 	command.setStoreQRCodeData(userInfo.WeChatPay)
				// 	command.setSelectSizeOfModuleForQRCode(8)
				// 	command.setPrintQRCode()
				// 	command.setPrintAndFeed(30);
				// 	command.setText('微信支付')
				// 	command.setPrintAndFeedRow(2);
				// }
				// 地址
				let address = this.printData.Address || ''
				// command.setSelectJustification(1); //居中
				command.setText(address)
				command.setPrintAndFeedRow(1);
				// command.setSelectJustification(1); //居中
				command.setText('赊货签提供技术支持')
				command.setPrintAndFeedRow(3);

				that.isReceiptSend = true;
				// 延时
				uni.hideLoading()
				that.prepareSend(command.getData());

			},

			//准备发送，根据每次发送字节数来处理分包数量
			prepareSend(buff) {
				console.log(buff);
				let that = this
				let time = that.oneTimeData
				let looptime = parseInt(buff.length / time);
				let lastData = parseInt(buff.length % time);
				console.log(looptime + "---" + lastData)
				this.looptime = looptime + 1;
				this.lastData = lastData;
				this.currentTime = 1;
				that.Send(buff)
			},
			//查询打印机状态
			queryStatus() {
				let command = esc.jpPrinter.Query();
				command.getRealtimeStatusTransmission(1);
			},
			//分包发送
			Send(buff) {
				let that = this
				let {
					currentTime,
					looptime: loopTime,
					lastData,
					oneTimeData: onTimeData,
					printerNum: printNum,
					currentPrint
				} = that;
				let buf;
				let dataView;
				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData)
					dataView = new DataView(buf)
					for (var i = 0; i < onTimeData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				} else {
					buf = new ArrayBuffer(lastData)
					dataView = new DataView(buf)
					for (var i = 0; i < lastData; ++i) {
						dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i])
					}
				}
				console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)
				let {
					BLEInformation
				} = that.Bluetooth;

				plus.bluetooth.writeBLECharacteristicValue({
					deviceId: BLEInformation.deviceId,
					serviceId: BLEInformation.writeServiceId,
					characteristicId: BLEInformation.writeCharaterId,
					value: buf,
					success: function(res) {
						console.log(res)
					},
					fail: function(e) {
						console.log(e)
					},
					complete: function() {
						setTimeout(() => {
							currentTime++
							if (currentTime <= loopTime) {
								that.currentTime = currentTime;
								that.Send(buff)
							} else {
								uni.showToast({
									title: '已打印第' + currentPrint + '张',
									icon: 'none'
								})
								if (currentPrint == printNum) {
									that.looptime = 0;
									that.lastData = 0;
									that.currentTime = 1;
									that.isReceiptSend = false;
									that.isLabelSend = false;
									that.currentPrint = 1;
								} else {
									currentPrint++;
									that.currentPrint = currentPrint;
									that.currentTime = 1;
									that.Send(buff)
								}
							}
						}, that.dealy)
					}
				})
			},
			buffBindChange: function(res) { //更改打印字节数
				let index = res.detail.value
				let time = this.buffSize[index]
				this.buffIndex = index;
				this.oneTimeData = time;
			},
			printNumBindChange: function(res) { //更改打印份数
				let index = res.detail.value
				let num = this.printNum[index]
				this.printNumIndex = index;
				this.printerNum = num;
			},
		}
	}
</script>

<style lang="less">
	.input {
		text-align: top;
		width: 90%;
		height: 150px;
		margin-left: 4%;
		margin-right: 4%;
		margin-top: 10px;
		margin-bottom: 12px;
		border: 1px solid slategray;
	}

	.receiver_info_scroll_view {
		width: 90%;
		height: 200px;
		margin-left: 4%;
		margin-right: 4%;
		margin-top: 10px;
		margin-bottom: 25px;
		border: 1px solid black;
	}

	.result {
		width: 90%;
		height: 150px;
		border: 1px solid black;
		margin-left: 4%;
		margin-bottom: 4%;
		margin-top: 5%;
	}

	button {
		width: 90%;
		margin-left: 5%;
		margin-right: 5%;
	}

	.switch {
		float: right;
		margin-right: 20px;
		margin-bottom: 16px;
	}

	text {
		color: #fff;
		display: block;
	}

	input {
		color: gainsboro;
		float: left;
	}

	.v_net_ssid {
		width: 100%;
		background: #fff;
	}

	.v_net_passw {
		width: 100%;
		background: antiquewhite;
	}

	.swiper {
		width: 100%;
		height: 100%;
	}
</style>